#! /usr/bin/env python3

import argparse
import re

DEFAULT_SEPARATOR = ','

def get_str_between_quotes(full_str):
    return re.findall('"([^"]*)"', full_str)[0]

def get_revisions(fname):
    revs_dict = {}
    with open(fname, 'r') as f:
        for line in f:
            name = None
            rev = None
            if 'project' not in line:
                continue
            for prop in line.split():
                if '=' not in prop:
                    continue
                prop_name, prop_val = prop.split('=')
                if prop_name == 'name':
                    name = get_str_between_quotes(prop_val)
                elif prop_name == 'revision':
                    rev = get_str_between_quotes(prop_val)
            if name and rev:
                revs_dict[name] = rev
    return revs_dict

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description = 'Get differences between two manifests. '
        'Return format "<component><separator><new_rev><separator><old_rev>"')
    parser.add_argument('new_manifest',
                        help='Manifest for the current compiler version')
    parser.add_argument('old_manifest',
                        help='Manifest for the previous compiler version')
    parser.add_argument('-s', '--separator',
                        help='Output separator. Default value is "{}"'.format(DEFAULT_SEPARATOR))
    args = parser.parse_args()
    output_separator = args.separator if args.separator else DEFAULT_SEPARATOR

    new_revs = get_revisions(args.new_manifest)
    old_revs = get_revisions(args.old_manifest)
    for name in set([*old_revs, *new_revs]):
        old_rev = old_revs.get(name, None)
        new_rev = new_revs.get(name, None)
        if new_rev != old_rev:
            print('{0}{1}{2}{1}{3}'.format(name, output_separator, new_rev, old_rev))

